"""
call_soon、call_later、call_at、call_soon_threadsafe
"""

import asyncio


def callback(sleep_times):
    print("sleep {} success".format(sleep_times))


def stop_loop(loop):
    # 停止事件循环
    loop.stop()


def use_call_soon():
    loop = asyncio.get_event_loop()
    loop.call_soon(callback, 2)
    loop.call_soon(stop_loop, loop)
    loop.run_forever()
    # 输出结果：
    """
    sleep 2 success
    """


def use_call_later():
    loop = asyncio.get_event_loop()

    # call_later会根据延时时间进行顺序执行
    loop.call_later(2, callback, 2)
    loop.call_later(1, callback, 1)
    loop.call_later(3, callback, 3)

    loop.call_later(4, stop_loop, loop)
    loop.run_forever()
    # 输出结果：
    """
    sleep 1 success
    sleep 2 success
    sleep 3 success
    """


def use_call_at():
    loop = asyncio.get_event_loop()

    now = loop.time()

    # call_later会根据延时时间进行顺序执行
    loop.call_at(now + 2, callback, 2)
    loop.call_at(now + 1, callback, 1)
    loop.call_at(now + 3, callback, 3)

    loop.call_at(now + 4, stop_loop, loop)
    loop.run_forever()
    # 输出结果：
    """
    sleep 1 success
    sleep 2 success
    sleep 3 success
    """


def use_call_soon_threadsafe():
    loop = asyncio.get_event_loop()
    loop.call_soon_threadsafe(callback, 2)
    loop.call_soon_threadsafe(stop_loop, loop)
    loop.run_forever()
    # 输出结果：
    """
    sleep 2 success
    """


if __name__ == '__main__':
    # use_call_soon()
    # use_call_later()
    # use_call_at()
    use_call_soon_threadsafe()
